<template>
  <el-tree
    v-loading="loading"
    ref="tree"
    :props="props"
    :data="menuTree"
    :default-checked-keys="menusId"
    node-key="id"
    show-checkbox
    check-strictly
    default-expand-all
    @check-change="handleCheckChange">
  </el-tree>
</template>

<script>
import { getMenuTree } from '@/api/system'

export default {
  name: 'MenuTree',
  props: {
    menusId: { // 角色的menusid ['menu1ID', 'menu2ID', ...]
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      menuTree: [],
      props: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    menusId: {
      handler(value) {
        if (!value) {
          this.loading = true
          this.clearChecked()
        } else {
          this.loading = false
        }
      },
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      const res = await getMenuTree()
      this.menuTree = res.data
    },

    clearChecked() {
      this.$refs.tree.setCheckedKeys([])
    },

    handleCheckChange() {
      this.$emit('update:menusId', this.$refs['tree'].getCheckedKeys())
    }
  }
}
</script>
